<template>
  <page-meta :root-font-size="$rootFontSize"></page-meta>
  <view>
    <!--找回密码-->
    <view class="mx-9 pt-32">
      <!--获取验证码-->
      <view v-if="isShow">
        <u--form :model="form" :rules="rules" ref="form" errorType="toast">
          <u-form-item class="px-5 rounded-full bg-inputGray" prop="phone">
            <u--input
              v-model="form.phone"
              type="number"
              shape="circle"
              border="none"
              fontSize="32rpx"
              color="#333333"
              placeholderStyle="color: #999999"
              placeholder="手机号"
              clearable
            >
            </u--input>
          </u-form-item>
          <u-form-item class="px-5 rounded-full bg-inputGray mt-4" prop="vcode">
            <!-- 注意：由于兼容性差异，如果需要使用前后插槽，nvue下需使用u--input，非nvue下需使用u-input -->
            <u-input
              v-model="form.vcode"
              type="number"
              shape="circle"
              border="none"
              fontSize="32rpx"
              color="#333333"
              placeholderStyle="color: #999999"
              placeholder="短信验证码"
              clearable
            >
              <template slot="suffix">
                <u-code
                  ref="uCode"
                  @change="codeChange"
                  @end="codeEnd"
                  :seconds="seconds"
                  changeText="X秒重新获取"
                  class="text-light text-sm"
                ></u-code>
                <view
                  @tap="getCode"
                  :text="tips"
                  class="text-sm text-primary"
                  >{{ tips }}</view
                >
              </template>
            </u-input>
          </u-form-item>
        </u--form>
        <view
          class="common-btn bg-primary text-center rounded-full text-white mt-9"
          @click="toReset"
          >确认</view
        >
      </view>
      <!--重置密码-->
      <view v-else>
        <u--form :model="forms" :rules="rulesPwd" ref="forms" errorType="toast">
          <u-form-item class="px-5 rounded-full bg-inputGray" prop="pwd">
            <u--input
              v-model="forms.pwd"
              type="password"
              shape="circle"
              border="none"
              fontSize="32rpx"
              color="#333333"
              placeholderStyle="color: #999999"
              placeholder="新密码"
              clearable
            >
            </u--input>
          </u-form-item>
        </u--form>
        <view
          class="common-btn bg-primary text-center rounded-full text-white mt-9"
          @click="onReset"
          >提交</view
        >
      </view>
    </view>
    <web-view :src="myUrl" @message="handleMessage" v-if="isWeb"></web-view>
  </view>
</template>

<script>
import { resetPwdValid, modifyPwd } from '../../services/user-details';
import { sendCode, sendVcodeLog } from '../../../services/user';

export default {
  data() {
    return {
      //webview页面携带参数天御行为验证码AppId
      myUrl:
        '/static/html/index.html?id=' +
        uni.getStorageSync('autoBuy' + uni.getStorageSync('autoBuy-platformId'))
          .captchaAppId
          ? uni.getStorageSync(
              'autoBuy' + uni.getStorageSync('autoBuy-platformId')
            ).captchaAppId
          : process.env.VUE_APP_SDK_APP_ID,
      //是否显示webview
      isWeb: false,
      isShow: true,
      tips: '',
      canGetCode: false,
      seconds: 60,
      tempToken: '',
      form: {
        phone: '',
        vcode: '',
      },
      forms: {
        pwd: '',
      },
      rules: {
        phone: [
          {
            type: 'string',
            required: true,
            message: '请输入手机号',
          },
          {
            validator: (rule, value, callback) => {
              return this.$u.test.mobile(value);
            },
            message: '手机号码不正确',
          },
        ],
        vcode: {
          required: true,
          message: '请输入短信验证码',
        },
      },
      rulesPwd: {
        pwd: {
          required: true,
          message: '请输入新密码',
        },
      },
    };
  },
  onLoad() {},
  methods: {
    //发送行为验证码日志(密-明)
    async _sendVcodeLog() {
      let params = {
        phone: this.form.phone,
        vcodeType: 'pcode',
      };
      const { code, data } = await sendVcodeLog(params);
      if (code != 200) return;
      //console.log(data);
    },
    //路由跳转
    goTo(url) {
      this.$Router.push({
        name: url,
      });
    },
    //获取文字
    codeChange(text) {
      this.tips = text;
    },
    codeEnd() {
      this.canGetCode = false;
    },
    //获取验证码 => 天御行为验证码
    async getCode() {
      if (this.form.phone == '') {
        uni.showToast({
          title: '请输入手机号',
          icon: 'none',
        });
        return;
      }
      if (!this.$u.test.mobile(this.form.phone)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none',
        });
        return;
      }
      //#ifdef H5
      this.$Captcha.show();
      uni.$on('gitTicket', (res) => {
        this.getCodeTo(res);
        uni.$off('gitTicket');
      });
      //#endif
      //#ifdef APP-PLUS
      this.isWeb = true;
      //#endif
    },
    //获取验证码
    async getCodeTo(res) {
      //短信接口方法
      //console.log(res);
      if (res.ret != 0) return;
      let params = {
        captchaVO: {
          randstr: res.randstr,
          ticket: res.ticket,
        },
        phone: this.form.phone,
        smsType: 'forgetpwd',
      };
      const { code, data } = await sendCode(params);
      if (code != 200) return;
      this.seconds = data;
      this._sendVcodeLog();
      if (this.$refs.uCode.canGetCode) {
        uni.showLoading({
          title: '正在获取验证码',
        });
        setTimeout(() => {
          uni.hideLoading();
          uni.$u.toast('验证码已发送');
          this.canGetCode = this.$refs.uCode.canGetCode;
          this.$refs.uCode.start();
        }, 1000);
      } else {
        uni.$u.toast('倒计时结束后再发送');
      }
    },
    //确认
    async toReset() {
      try {
        await this.$refs.form.validate();
        let params = {
          vcode: this.form.vcode,
          phone: this.form.phone,
        };
        const { code, data } = await resetPwdValid(params);
        if (code != 200) return;
        this.tempToken = data.tempToken;
        this.isShow = false;
      } catch (error) {
        console.error(error);
      }
    },
    //重置密码
    async onReset() {
      try {
        await this.$refs.forms.validate();
        let params = {
          phone: this.form.phone,
          passwd: this.forms.pwd,
          tempToken: this.tempToken,
        };
        //console.log(params);
        const { code, data } = await modifyPwd(params);
        //console.log(code, data);
        if (code != 200) return;
        uni.$u.toast('恭喜您！重置成功');
        setTimeout(() => {
          this.$Router.push({
            name: 'login',
          });
        }, 800);
      } catch (error) {
        console.error(error);
      }
    },
    //html/index页面发来的消息
    handleMessage(e) {
      uni.setNavigationBarTitle({
        title: '找回密码',
      });
      let data = e.detail.data[0];
      if (data.ret === 2) {
        this.isWeb = false;
      }
      if (data.ret === 0) {
        this.getCodeTo(data);
        this.isWeb = false;
      }
    },
  },
};
</script>

<style></style>
